﻿// BooTasky is a small tools which use RememberTheMilk web services.
// Copyright (C) BooTasky of Yan-ren Tsai
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

namespace BooTasky

import System
import System.Collections.Generic
import System.Net 
import System.Windows.Forms
import System.Diagnostics
import Microsoft.Win32
import RtmNet 

class RtmBackend(IService, IConfiguration, IAuthentication):
"""Description of RtmService"""
	apiKey = "0ae887b46e1278a295f6b7ffca739bef"
	sharedSecret = "302be0a7e528a5a3"
	_rtm as Rtm
	_rtmAuth as Auth
	_timeline as string

	def constructor():
		Load()
		
		_rtm = Rtm(apiKey, sharedSecret)
		_rtm.Proxy = WebProxy.GetDefaultProxy()
		_rtm.Proxy.Credentials = CredentialCache.DefaultCredentials

#region IConfiguration implementation.
	_authToken as string
	_userName as string
	_userId as string
	_isAuthenticated as bool
	
	private _softwareKey as string = "HKEY_CURRENT_USER\\Software\\bootasky\\"

	def Load():
		_isAuthenticated = Registry.GetValue( _softwareKey, "IsAuthenticated", 0 )==1
		_authToken = Registry.GetValue( _softwareKey, "AuthToken", null )
		_userName = Registry.GetValue( _softwareKey, "UserName", null )
		_userId = Registry.GetValue( _softwareKey, "UserId", null )
		
	def Save():
		Registry.SetValue( _softwareKey, "AuthToken", _authToken )
		Registry.SetValue( _softwareKey, "UserName", _userName )
		Registry.SetValue( _softwareKey, "UserId", _userId )
		boolValue = 0
		if _isAuthenticated:
			boolValue=1
		Registry.SetValue( _softwareKey, "IsAuthenticated", boolValue )
#endregion

#region IAuthentication implementation
	IsAuthenticated as bool:
		get:
			return _isAuthenticated
		
	def StartAuthentication() as bool:
		frob = _rtm.AuthGetFrob()
		url = _rtm.AuthCalcUrl(frob, AuthLevel.Delete)
		if BrowserDialog( url ).ShowDialog()==DialogResult.OK:
			_rtmAuth = _rtm.AuthGetToken(frob)
			if _rtmAuth!=null:
				_authToken = _rtmAuth.Token
				Debug.WriteLine( "authToken = ${_authToken}" )
				if _rtmAuth.User!=null:
					_userName = _rtmAuth.User.Username
					_userId = _rtmAuth.User.UserId
					Debug.WriteLine( "userName=${_userName} userId=${_userId}" )
			return true
		return false
		
	def EndAuthentication():
		_isAuthenticated = true
#endregion

#region IService Implementation.
	def Initialize():
		if _authToken!=null:
			try:
				_rtm = Rtm(apiKey, sharedSecret, _authToken)
				_rtm.Proxy = WebProxy.GetDefaultProxy()
				_rtm.Proxy.Credentials = CredentialCache.DefaultCredentials
				_rtmAuth = _rtm.AuthCheckToken(_authToken)
				_timeline = _rtm.TimelineCreate();
			except e:
				Debug.WriteLine( e.Message )
				_rtm = null
				_rtmAuth = null

	_categoryHash = {}
	
	def GetCategory() as IEnumerable of ICategory:
		for list in _rtm.ListsGetList().listCollection:
			category = RtmCategory(list)
			_categoryHash[ list.ID ] = category
			yield category

	def GetTasks( id as string ) as IEnumerable[of ITask]:
		tasks as Tasks = null
		//try:
		tasks = _rtm.TasksGetList( id )
		//except e as Exception:
		//	Debug.WriteLine( e.Message )

		for list in tasks.ListCollection:
			for series in list.TaskSeriesCollection:
				yield RtmTask( series, _categoryHash[id] )
		
#endregion
